import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Between, IsNull } from 'typeorm';
import { Task } from '../tasks/entities/task.entity';
import { User } from '../users/entities/user.entity';
import { Category } from '../categories/entities/category.entity';
import { subDays, startOfDay, endOfDay, format } from 'date-fns';

@Injectable()
export class StatisticsService {
  constructor(
    @InjectRepository(Task)
    private tasksRepository: Repository<Task>,
    @InjectRepository(Category)
    private categoriesRepository: Repository<Category>,
  ) {}

  async getCompletionTrend(user: User, days: number = 7): Promise<any[]> {
    const result: any[] = [];
    const today = new Date();

    for (let i = days - 1; i >= 0; i--) {
      const date = subDays(today, i);
      const startDate = startOfDay(date);
      const endDate = endOfDay(date);

      const totalTasks = await this.tasksRepository.count({
        where: {
          user: { id: user.id },
          createdAt: Between(startDate, endDate),
        },
      });

      const completedTasks = await this.tasksRepository.count({
        where: {
          user: { id: user.id },
          createdAt: Between(startDate, endDate),
          completed: true,
        },
      });

      const completionRate =
        totalTasks > 0 ? (completedTasks / totalTasks) * 100 : 0;

      result.push({
        date: format(date, 'yyyy-MM-dd'),
        totalTasks,
        completedTasks,
        completionRate: Math.round(completionRate * 100) / 100,
      });
    }

    return result;
  }

  async getCategoryDistribution(user: User): Promise<any[]> {
    const categories = await this.categoriesRepository.find({
      where: { user: { id: user.id } },
      relations: ['tasks'],
    });

    // 获取没有分类的任务数量
    const tasksWithoutCategory = await this.tasksRepository.count({
      where: {
        user: { id: user.id },
        category: IsNull(),
      },
    });

    const result = categories.map((category) => ({
      id: category.id,
      name: category.name,
      color: category.color,
      count: category.tasks.length,
    }));

    // 添加未分类的任务
    if (tasksWithoutCategory > 0) {
      result.push({
        id: 0,
        name: '未分类',
        color: '#CCCCCC',
        count: tasksWithoutCategory,
      });
    }

    return result;
  }

  async getTasksSummary(user: User): Promise<any> {
    const totalTasks = await this.tasksRepository.count({
      where: { user: { id: user.id } },
    });

    const completedTasks = await this.tasksRepository.count({
      where: {
        user: { id: user.id },
        completed: true,
      },
    });

    const pendingTasks = await this.tasksRepository.count({
      where: {
        user: { id: user.id },
        completed: false,
      },
    });

    // 获取今天到期的任务
    const today = new Date();
    const startOfToday = startOfDay(today);
    const endOfToday = endOfDay(today);

    const dueTodayTasks = await this.tasksRepository.count({
      where: {
        user: { id: user.id },
        dueDate: Between(startOfToday, endOfToday),
        completed: false,
      },
    });

    // 获取过期的任务
    const overdueTasks = await this.tasksRepository.count({
      where: {
        user: { id: user.id },
        dueDate: Between(new Date(0), startOfToday),
        completed: false,
      },
    });

    return {
      totalTasks,
      completedTasks,
      pendingTasks,
      dueTodayTasks,
      overdueTasks,
      completionRate:
        totalTasks > 0
          ? Math.round((completedTasks / totalTasks) * 10000) / 100
          : 0,
    };
  }
}
